﻿

const { message } = antd
var params = {
    messageTest: {
        value: ''
    }
}
params.messageTest.value = message
params.messageTest.value.config({
    top: `10vh`,
    duration: 7,
    maxCount: 1,
    rtl: true,
});
//获取参数
export function queryURLParams() {
    const searchParams = window.location.search.substring(1).split("&");
    const params = {};

    for (const param of searchParams) {
        const [key, value] = param.split("=");
        params[key] = value;
    }

    return params;
}
export async function downloadRemoteFile(filename, url) {
    try {
        const response = await fetch(url);
        if (response.statusText == 'ok') {
            const blob = await response.blob();

            if (navigator.msSaveBlob) { // IE 10+
                navigator.msSaveBlob(blob, filename);
            } else {
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = filename;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(link.href); // 清理内存
            }
        } else {
            alert('网络繁忙')
        }
 
    } catch (error) {
  
        console.error('Failed to download file:', error);
    }
}

export const dealmark = (number,maxmark) => {

    if (number < 0) {
        return 0
    }
    return Number(Number(number).toFixed(2))
}

export const  sumByKey=(array, key) => {
    if (!Array.isArray(array)) return 0;

    return array.reduce((total, item) => {
        const value = item[key];
        // 如果值是数字则累加，否则忽略
        return typeof value === 'number' ? total + value : total;
    }, 0)
}


// 防抖函数
export function debounce(func, delay) {
    let timer = null;
    return function (...args) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(this, args);
        }, delay);
    };
}

// 节流函数
export function throttle(func, threshold) {
    let last = null;
    let timer = null;
    return function (...args) {
        const now = Date.now();
        if (last && now < last + threshold) {
            if (timer) clearTimeout(timer);
            timer = setTimeout(() => {
                last = now;
                func.apply(this, args);
            }, threshold);
        } else {
            last = now;
            func.apply(this, args);
        }
    };
}









export const getBrowserInfo = () => {

        return new Promise((resolve, rej) => {

            var ua = navigator.userAgent;
            var edgeVersion;
            var chromeVersion;

            const t = (o) => {
                if (o < 86) {
                    let c = window.confirm(`您的浏览器版本过低，请点击“确认”，然后在右上角“下载”目录，运行浏览器安装程序，谢谢！`)
                    if (c) {
                        downloadRemoteFile('ChromeSetup.exe', 'http://10.5.0.121:8031/File/Download/ChromeSetup64.exe')
                        return 1
                    } else {
                        alert('您已取消下载新版本浏览器，如需要更新，请刷新页面，谢谢！')
                        return 0
                    }
                }

            }

            try {
                // 检测Edge浏览器
                if (/Edg\/([\d.]+)/.test(ua)) {
                    edgeVersion = RegExp.$1;
                    console.log('This is Microsoft Edge ' + edgeVersion);
                    let res = t(edgeVersion.split('.')[0], 1)
                    res == 1 ? resolve(1) : rej(0)
                }

                // 检测Chrome浏览器
                else if (/Chrome\/([\d.]+)/.test(ua) || /CriOS\/([\d.]+)/.test(ua)) {
                    chromeVersion = RegExp.$1;
                    let res = t(chromeVersion.split('.')[0], 2)
                    res == 1 ? resolve(1) : rej(0)
                }
            } catch (err) {
                console.log(err)
            }
     
        })
    

}


export const CONSTPARAMSDATA = {
    typelist: [{
        label: "部门级",
        value: 1
    }, {
        label: "公司级",
        value: 2
    }]
}


//处理后端时间
export function dealTime(str, format="YYYY-MM-DD") {
    if (str) {
        return dayjs(parseInt(str.match(/\/Date\((\d+)\)\//)[1], 10)).format(format);
    } else {
        console.log('时间戳字符为空')
    }
    
}


//获取近三年
export function getRecentYears() {
    const currentYear = new Date().getFullYear();
    return [currentYear - 2,currentYear - 1, currentYear, currentYear + 1, currentYear + 2].map(e => {
        return {
            label: e,
            value: e
        }
    })

}

//获取12个月
export function getMonthList() {
    let list=[]
    for (let i = 1; i < 13; i++) {
        list.push({
            label: `${i}月`,
            value:i
        })
    }
    return list
     
}

//是否图片
export function isImageFile (url) {
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.svg', '.webp','.pdf'];
    const fileExtension = url && url.substring(url.lastIndexOf('.')).toLowerCase();
    return imageExtensions.includes(fileExtension);
}

//ppe文件删除
export function IDeletePPEFile(Request,id) {
    return new Promise((resolve, rej) => {
        Request({
            url: "/PPE/DeletePPEFile",
            method: 'post',
            data: {
                FileId: id,
            }
        }).then(res => {
            resolve(res)
        }).catch(err => {
            rej(err)
        });
    })
}
export function DeleteModuleFile(Request, id) {
    return new Promise((resolve, rej) => {
        Request({
            url: "/SafetySystem/DeleteModuleFile",
            method: 'post',
            data: {
                FileId: id,
            }
        }).then(res => {
            resolve(res)
        }).catch(err => {
            rej(err)
        });
    })
}



export const saveTime=1000 * 60 * 5

//简易深拷贝
export function easyCopy(item) {
    return JSON.parse(JSON.stringify(item))

}

//获取部门
export function IgetDeptList(Request) {
    return new Promise((resolve,rej) => {
        Request({
            url: "/SystemConfig/GetDepartmentList",
            method: 'post',

        }).then(res => {
            let list = res.Data&&res.Data.map(e => {
                return {
                    label: e.DepartmentName,
                    value: e.Id
                }
            })
            resolve(list)
        });
    })

}

//获取成员
export function IgetUserList(Request) {
    return new Promise((resolve, rej) => {
        Request({
            url: "/PPE/getUserList",
            method: 'post',

        }).then(res => {



            let list = res.Data && res.Data.map(e => {
                return {
                    label: e.Email ? `${e.UserName}(${e.UserNo}) [${e.Email || ''}]` : `${e.UserName}(${e.UserNo}) [暂无邮箱]` ,
                    value: e.UserNo,

                }
            })
            resolve(list)
        });
    })

}



//履职删除文件
export function DeleteFormFile(Request, id) {
    return new Promise((resolve, rej) => {
        Request({
            url: "/performance/DeleteFormFile",
            method: 'post',
            params: {
                FileId: id
            }
        }).then(res => {
            if (res.Code == 100) {
                resolve(res)
            } 
        
        }).catch(err => {
        })
    })

}




//fetch文件下载
export function downloadfun(name, url) {
    return new Promise((resolve, rej) => {
        fetch(url)
            .then(response => {
                if (!response.ok) {
                    params.messageTest.value.info('下载失败，请检查网络')
                    rej()
                    throw new Error('Network response was not ok');
                }
                return response.blob();
            })
            .then(blob => {
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = name;
                link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
                // 兼容性处理：对于不支持 click() 方法的浏览器
                if (document.createEvent) {
                    const event = document.createEvent('MouseEvents');
                    event.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                    link.dispatchEvent(event);
                } else {
                    link.click();
                }
                resolve()
            })
            .catch(error => {
                console.error('There was a problem with the fetch operation:', error);
            });

    })

}

//履职删除文件
export function DeleteFormFileItem(Request, id) {
    return new Promise((resolve, rej) => {
        Request({
            url: "/performance/DeleteItemFile",
            method: 'post',
            params: {
                FileId: id
            }
        }).then(res => {
            if (res.Code == 100) {
                resolve(res)
            } 
        }).catch(err => {
        })
    })

}
export const handlePdfExport= (name,ptheadList,pdata) => {
    var theadList = ptheadList|| [
        {
            name: "姓名",
            props: "Name",
        },
        {
            name: "工号",
            props: "UserNo",
        },
        {
            name: "职位",
            props: "Title",
        },
        {
            name: "职务",
            props: "JobTitle",
        },
        {
            name: "联系方式",
            props: "Phone",
        },
        {
            name: "备注",
            props: "Remark",
        },

    ];
    function renderTableHeader() {
        const thead = document
            .getElementById("dataTable")
            .getElementsByTagName("thead")[0];
        thead.innerHTML = "";
        const headerRow = thead.insertRow();
        theadList.forEach((text) => {
            const th = document.createElement("th");
            th.textContent = text.name;
            headerRow.appendChild(th);
        });
    }
    // 渲染表格数据
    async function renderTable() {
        const response = pdata;
        const table = document
            .getElementById("dataTable")
            .getElementsByTagName("tbody")[0];
        table.innerHTML = ""; // 清空现有数据
        response.forEach((item) => {
            const row = table.insertRow();
            let propsList = theadList.map((e) => e.props);
            propsList.forEach((e, i) => {
                row.insertCell(i).textContent = item[e];
            });
        });
    }

    // 创建表格元素
    function createTableElement() {
        const container = document.getElementById("tableContainer");
        const table = document.createElement("table");
        table.style.position = "absolute";
        table.style.left = "-9999px";
        table.id = "dataTable";
        table.innerHTML = "<thead></thead><tbody></tbody>";
        container.appendChild(table);
    }
    createTableElement();
    renderTableHeader();
    renderTable();
    return new Promise((resolve,rej) => {
        setTimeout(() => {
            exportToPDF(name)
            resolve()
        }, 1000)
    })
 


}
export const popShowCom = (text, name, isline = false) => {
    let hdiv;
    if (!isline) {
         hdiv = (content) => h('div', {
            style: `max-width: 600px;
                          `
        }, {
            default: () => content
        })
    } else {
        let divs = text.map((e) => {
            return h('div', {
            }, {
                default: () => e
            })
        })
         hdiv = () => h('div', {
            style: `max-width: 600px;
                          `
        }, {
            default: () => [...divs]
        })
    }




    const tag = (text, desc) => h(antd.Tag, {
        color: "#108ee9",
        style: desc ? "cursor:pointer" : ""
    }, { default: () => text })


    const pop = (text, desc,name) => h(antd.Popover, {
        title: name|| '部门',
        content: hdiv(desc),
    }, () => [tag(text, desc)]);


    return h('div', {
        style: "display:flex;width:120px;height:auto;margin:0 auto;justify-content: center;"
    }, {
        default: () => [pop(text.length, text.length > 0 ? text.toString() : '-', name)]
    })

}


export const showDeleteConfirm = ({ title, content, okText = '确定', okType = '', cancelText = '取消', okFun = () => { console.log('ok'); }, cancelFun = () => { console.log('Cancel'); } }) => {
    antd.Modal.confirm({
        title: title,
        content: content,
        okText: okText,
        okType: okType,
        cancelText: cancelText,
        onOk() {
            okFun()
        },
        onCancel() {
            cancelFun()
        },
    })
}

export const previewCom = (params, methods) => {
    return {
        imageModel: {
            template: `
 <a-image :width="200"
                     :style="{ display: 'none',zIndex:100 }"
                     :preview="{visible:previewInfo.previewShow,onVisibleChange:(value)=>{ previewInfo.previewShow=value}}" :src="previewInfo.imgUrl"></a-image>`
            ,
            setup() {
                return {
                    ...params,
                    ...methods,
                };
            }
        },
        pdfPopModel: {
            template: `
           <a-modal v-model:open="previewInfo.pdfOpen" width = "80%" title="PDF预览" v-on:ok="previewInfo.pdfOpen=false" >
<div style='height:700px'>
                <embed id="pdfviewscreen" :src="previewInfo.pdfUrl" type="application/pdf" width="100%" style="height:100%;" />

</div>
            </a-modal >
`,
            setup() {
                return {
                    ...params,
                    ...methods,
                };
            }
        },


    }


}


export function isAllFieldsFilled(obj) {
    return Object.values(obj).every(
        value => value !== null && value !== undefined && value !== ''
    );
}

export function isArrayObjectsAllFilled(arr) {
    if (!Array.isArray(arr)) return false;
    return arr.every(obj => {
        if (typeof obj !== 'object' || obj === null) return false;
        return isAllFieldsFilled(obj);
    });
}

export const imageBaseUrl = '../'